$(document).ready(function() {	 															
							 $('#_interventionDate').datepicker({
										showOn: 'button',
										buttonImage: '/css/custom-theme/images/calendar.gif',
										buttonImageOnly: true
									});
							 
							 $('#_save').click(function() {
								 
								 if (!checkBasicFields())
									 return false;
								 
								 advancedRulesCheck = true;
								 switch($.trim($('#_orderedDrugText').val()))
								 {
								 	case 'TPN - TPN':
								 	case 'Patient\'s Own Meds - Patient\'s Own Meds':
								 		advancedRulesCheck = false;
								 		break;
								 }
								 
								 
								 if (advancedRulesCheck)
									 if (!checkAdvancedFields())
										 return false;
								 
								 	var pathname = window.location.pathname;
								 	var parsedPathname = pathname.substr(pathname.length - 3, 3);
								 	if (parsedPathname == 'add') //It's always ok to add
								 		return true;
								 	
								 	//Editing a record.  Check to see if it has been modified
								 	var ciId = $('input[name=intervention_id]').val();
								 	if (record_is_modified('intervention', ciId))
								 	{
								 		if (!confirmOverwrite())
								 		{
								 			window.location.reload();
								 			return false;
								 		}
								 	}
									});

							$('#_close').click(function() {
								if (!confirmNavigation())
									return false;
								window.opener.location.reload();
								window.close();
								return false;
								});
							
							$('#_clearForm').click(function() {
								clear_form();
								});
	
							$('#_patientIdNumber').autocomplete({
									minLength: 2,
									source: function(req, add){autocompletePatientSource(req,add);},
									select: function(event, ui){autocompletePatientSelect(event,ui);}
							});
	
							 $('#_orderedDrugText').autocomplete({
									 minLength: 3,
									 source: function(req, add){autocompleteSource(req,add);},
									 select: function(event, ui){autocompleteSelect(event,ui, $('#_orderedDrugText'), $('#_orderedUnitCost'),$('#_orderedDrugFrequencyId'), $('#_orderedDosesPerDay'), $('input[name=ordered_default_doses_per_day]'), $('#_orderedCostPerDay'), $('input[name=ordered_drug_id]') );}
							 });  
	
							 $('#_recommendedDrugText').autocomplete({
									 minLength: 3,
									 source: function(req, add){autocompleteSource(req,add);},
									 select: function(event, ui){autocompleteSelect(event,ui, $('#_recommendedDrugText'), $('#_recommendedUnitCost'),$('#_recommendedDrugFrequencyId'), $('#_recommendedDosesPerDay'), $('input[name=recommended_default_doses_per_day]'), $('#_recommendedCostPerDay'), $('input[name=recommended_drug_id]') );}
							 });
	
							 ///////////////////////////////////////////////////////////////
							 //START:  Set functions for changing form state based on user selection 
							 /////////////////////////////////////////////////////////////// 
							 $('#_interventionCode').change(function(){
								 change_recommended_drug_fieldset_state();
						 		});
	
							 $('#_orderedDrugFrequencyId').change(function(){
								 change_doses_per_day($(this), $('#_orderedDosesPerDay'), $('input[name=ordered_default_doses_per_day]'));
						 		});
	
							 $('#_orderedDrugFrequencyId').keyup(function(){
								 change_doses_per_day($(this), $('#_orderedDosesPerDay'), $('input[name=ordered_default_doses_per_day]'));
						 		});
	
							 $('#_recommendedDrugFrequencyId').change(function(){
								 change_doses_per_day($(this), $('#_recommendedDosesPerDay'), $('input[name=recommended_default_doses_per_day]'));
						 		});
	
							 $('#_recommendedDrugFrequencyId').keyup(function(){
								 change_doses_per_day($(this), $('#_recommendedDosesPerDay'), $('input[name=recommended_default_doses_per_day]'));
						 		});
	
							 $('#_interventionCodeListBox').dblclick(function() {
									$('#_interventionCode').val($(this).val());
									change_recommended_drug_fieldset_state();
									handleFormChanged();
									//Clear the selection
									$(this).val('-1');
						 		});
							 
							 $('.unit-cost').blur(function(){
								 $(this).val(formatToCurrency($(this).val()));
						 		});	
							 $('#_orderedDosesPerDay').blur(function(){
								 //User could change value so set new value equal the hidden field
								 $('input[name=ordered_default_doses_per_day]').val($(this).val())
								 calculate_cost_per_day('ordered');
						 		});
							 $('#_recommendedDosesPerDay').blur(function(){
								//User could change value so set new value equal the hidden field
								$('input[name=recommended_default_doses_per_day]').val($(this).val())
								calculate_cost_per_day('recommended');
						 		});	
							 
							 $('.tx-days-table input').blur(function(){
								 calculate_days_remaining();
							 }
							 );

	
							///////////////////////////////////////////////////////////////
							//END:  Set functions for changing form state based on user selection 
							/////////////////////////////////////////////////////////////// 
						 		
							 
							 //Start JQuery Help Dialogs
							 $('#status-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#intervention-code-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#drug-frequency-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#cost-per-day-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#risk-mitigation-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#days-of-tx-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#current-tx-day-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 $('#days-remaining-help-dialog-message').dialog({
									 autoOpen: false,modal: true,show: 'blind',buttons: {Ok: function() {$(this).dialog('close');}}
								 });
							 //End JQuery Help Dialogs
	
	
							 
							 $('.ui-state-default').hover(
											 function(){ $(this).addClass('ui-state-hover'); }, 
											 function(){ $(this).removeClass('ui-state-hover'); }
										 );
							$('.ui-state-default').click(function(){
									var dialogName;
	
	
									switch($(this).attr('id'))
									{
										case '_statusHelpDiv': 
											dialogName= '#status-help-dialog-message'; 
												break;
											case '_interventionCodeHelpDiv': 
													dialogName= '#intervention-code-help-dialog-message'; 
													break;
											case '_drugfrequencyHelpDiv': 
													dialogName= '#status-help-dialog-message'; 
														break;
											case '_drugfrequencyHelpDiv1':
											case '_drugfrequencyHelpDiv2':
												dialogName= '#drug-frequency-help-dialog-message';
												break;
											case '_costperdayHelpDiv1':
											case '_costperdayHelpDiv2':
												dialogName= '#cost-per-day-help-dialog-message';
												break;
											case '_riskmitigationHelpDiv': 
													dialogName= '#risk-mitigation-help-dialog-message'; 
														break;
											case '_daysOfTxHelpDiv': 
													dialogName= '#days-of-tx-help-dialog-message'; 
														break;
											case '_currentTxDayHelpDiv': 
													dialogName= '#current-tx-day-help-dialog-message'; 
														break;
											case '_daysRemainingHelpDiv': 
													dialogName= '#days-remaining-help-dialog-message'; 
														break;
													
												
									}
								$(dialogName).dialog('open');
								return false; 
							});
	
							$('.tx-days-input').keydown(function(event) {
								allowNumericInputOnly(event); 
							});
							
							//Call the function that has automatically generated javascript
							additional_javascript_doc_ready_functions();
	
							//The following code is used to determine if the form is dirty or not.	used in conjunction with common_form_functions.js 
							//http://www.mydogboris.com/2009/10/using-jquery-data-feature-to-detect-form-changes/
							$('#_ciForm input[type=text]').each(function (i) 
									{
										$(this).data('initial_value', $(this).val());
									});
	
							$('#_ciForm input[type=text]').keyup(function() 
									{
										if ($(this).val() != $(this).data('initial_value')) 
											handleFormChanged();
									});
	
							$('#_ciForm .editable').live('change paste', function() 
									{
									handleFormChanged();
									});
	
							//end dirty form code 
	
									//set validation for form
									$('#_ciForm').validate(
										{
											rules: 
											{
												patient_id_number: 'required',
												intervention_date: 
												{
													required: true,
													date: true
												},
												comment:'required'
											},
											messages: 
											{
												patient_id_number: 'required',
												intervention_date: 
												{
													required: 'required',
													date: 'invalid date'
												},
												comment:'required'
											}
										}
									);
							//end form validation
	
							//set default state of items
							change_recommended_drug_fieldset_state();
							change_doses_per_day($('#_orderedDrugFrequencyId'), $('#_orderedDosesPerDay'), $('input[name=ordered_default_doses_per_day]'));
							change_doses_per_day($('#_recommendedDrugFrequencyId'), $('#_recommendedDosesPerDay'), $('input[name=recommended_default_doses_per_day]'));
							
							calculate_cost_per_day('ordered');
							calculate_cost_per_day('recommended');
							calculate_days_remaining();
							calculate_intervention_savings();
							
							//Convert unit costs to currency
							$('#_orderedUnitCost').val(formatToCurrency($('#_orderedUnitCost').val()));
							$('#_recommendedUnitCost').val(formatToCurrency($('#_recommendedUnitCost').val()));
							
							
							$('#_patientIdNumber').focus();
	
							 }
	); //End of document ready

	function calculate_cost_per_day(cost_type)
	{
		if (cost_type == 'ordered')
		{
			var unit_cost = currencyToNumber($('#_orderedUnitCost').val());
			var units_per_dose = GetDrugFrequncyRatio(parseInt($('#_orderedDrugFrequencyId').val()));
			var doses_per_day = $('#_orderedDosesPerDay').val();
			var costPerDayInput = $('#_orderedCostPerDay')
		}
		else
		{
			var unit_cost = currencyToNumber($('#_recommendedUnitCost').val());
			var units_per_dose = GetDrugFrequncyRatio(parseInt($('#_recommendedDrugFrequencyId').val()));
			var doses_per_day = $('#_recommendedDosesPerDay').val();
			var costPerDayInput = $('#_recommendedCostPerDay')
		}
	
		costPerDayInput.val(formatToCurrency(unit_cost * units_per_dose * doses_per_day));
		calculate_intervention_savings();
	}

	//Put correct doses per day in the doses per day box
	function calculate_doses_per_day(drugfrequencySelect, drugDosesPerDay, defaultDosesPerDay)
	{
		var disabledText = $(drugfrequencySelect).val() != 1 ? 'disabled' : '' ;
		if (disabledText == 'disabled')
			drugDosesPerDay.val('1');
		else
			drugDosesPerDay.val(defaultDosesPerDay.val());
		
		$(drugDosesPerDay).attr('disabled',disabledText);
	}
	
	//Put correct doses per day in the doses per day box
	function change_doses_per_day(drugfrequencySelect, drugDosesPerDay, defaultDosesPerDay)
	{
		var disabledText = $(drugfrequencySelect).val() != 1 ? 'disabled' : '' ;
		if (disabledText == 'disabled')
			drugDosesPerDay.val('1');
		else
			drugDosesPerDay.val(defaultDosesPerDay.val());
		
		$(drugDosesPerDay).attr('disabled',disabledText);
		
		calculate_cost_per_day('ordered');
		calculate_cost_per_day('recommended');
		
	}

	//When user selects an intervention code, this function will be called to enable/disable the recommended drug.
	//State is determined if the Intervention code contains '(r); which stands for Risk Mitigation.
	function change_recommended_drug_fieldset_state()
	{
		var disabledText = $('#_interventionCode option:selected').text().indexOf('(r)') > 0 ? 'disabled' : '' ;
		$('.recommended-fieldset input').attr('disabled',disabledText);
		$('.recommended-fieldset select').attr('disabled',disabledText);
		$('.recommended-fieldset legend').attr('disabled',disabledText);
		
		$('.tx-days-fieldset input').attr('disabled',disabledText);
		$('.tx-days-fieldset select').attr('disabled',disabledText);
		$('.tx-days-fieldset legend').attr('disabled',disabledText);
		
		//TODO:  This only works in IE...not FF for some reason
		$('.calculated-fieldset input').attr('disabled',disabledText);
		$('.calculated-fieldset select').attr('disabled',disabledText);
		$('.calculated-fieldset legend').attr('disabled',disabledText);
		
	
		//Prevent accidentally setting recommended drug to enabled after changing intervention code type 
		if (disabledText != 'disabled')
			change_doses_per_day($('#_recommendedDrugFrequencyId'), $('#_recommendedDosesPerDay'), $('input[name=recommended_default_doses_per_day]'));
	}
	
	//Called when user selects a patient from the Autocomplete form
	function autocompletePatientSelect(event,ui)
	{
		$('input[name=patient_id]').val(ui.item.id);
		//var lineItem = this.id;
		//$('#patientId').val(ui.item.id);
		//localPatientIdNumber.val(this.id);
		//localUnitCost.val(ui.item.wholesale_each_cost);
		//localPatientIdNumber.val(ui.item.value);
	}

	//Called when user starts typing in the patient form 
	function autocompletePatientSource(req,add)
	{
			$.ajax({
					url: '/index.php/patient_list/lookup',
					dataType: 'json',
					type: 'POST',
					data: req,
					success:		
							function(data)
							{
									if(data.response =='true')
									{
											add(data.message);
									}
									else
											add(''); //No success, clear var
							}
			});
	}


	//Called when user selects a drug from the Autocomplete form 
	function autocompleteSelect(event,ui,localDrugText, localUnitCost, localDrugFrequencyId, localDosesPerDay, localDefaultDosesPerDay, localCostPerDay, localHiddenId)
	{
			var lineItem = this.id;
			localHiddenId.val(ui.item.id);
			localDrugText.val(ui.item.value);
			localUnitCost.val(ui.item.wholesale_each_cost);
	
			var drugFrequencySelectValue = 0
			if (ui.item.doses_per_day > 1)
				drugFrequencySelectValue = 1;
			else
			{
				drugFrequencySelectValue = (SetDrugFrequencyByRatio(ui.item.doses_per_day));
				$(localDosesPerDay).attr('disabled','');
			}
	
			localDrugFrequencyId.val(drugFrequencySelectValue);
			var dosesValue = ui.item.doses_per_day > 1 ? ui.item.doses_per_day : 1 ;
			localDosesPerDay.val(dosesValue);
	
			var calculatedCostPerDay =  currencyToNumber(localUnitCost.val()) * GetDrugFrequncyRatio(drugFrequencySelectValue) * dosesValue;
			calculatedCostPerDay = formatToCurrency(calculatedCostPerDay); 
			localCostPerDay.val(calculatedCostPerDay);
			
			
			localDefaultDosesPerDay.val(dosesValue);
	
	}

	//Called when starts typing a drug name 
	function autocompleteSource(req,add)
	{
			$.ajax({
					url: '/index.php/ajax/drug_list_lookup',
					dataType: 'json',
					type: 'POST',
					data: req,
					success:		
							function(data)
							{
									if(data.response =='true')
									{
											add(data.message);
									}
									else
											add(''); //No success, clear var
							}
			});
	}
	
	function calculate_days_remaining()
	{
		var daysOfTx = parseInt($('#_daysOfTx').val());
		var currentTxDay = parseInt($('#_currentTxDay').val());
		
		if (isNaN(daysOfTx) || isNaN(currentTxDay))
			$('#_daysRemaining').val('');
		else
		{
			var daysRemaining = daysOfTx - currentTxDay; 
			$('#_daysRemaining').val(daysRemaining);
		}
		
		calculate_intervention_savings();
	}
	function calculate_intervention_savings()
	{
		var daysRemaining = parseInt($('#_daysRemaining').val());
		var orderedCostPerDay = currencyToNumber($('#_orderedCostPerDay').val());
		var recommendedCostPerDay = currencyToNumber($('#_recommendedCostPerDay').val());
		
		if (isNaN(daysRemaining) || isNaN(orderedCostPerDay) || isNaN(recommendedCostPerDay))
			$('#_savings').val('');
		else
		{
			var savings = (orderedCostPerDay - recommendedCostPerDay) * daysRemaining;   
			$('#_savings').val(formatToCurrency(savings));
			$('#_savings').toggleClass('red-text', savings < 0);
			$('#_savings').toggleClass('calculated-input', savings >= 0);

		}
	}
	
	function clear_form()
	{
		$('select').val('');
		$('input').val('');
	}
	
	function checkBasicFields()
	{

		 if ($('input[name=patient_id]').val() == '')
		 {
			 window.alert('A valid patient must be selected before saving.');
			 $('#_patientIdNumber').focus();
			 return false;
		 }
		 
		 if ($('#_interventionCode').val() == '-1')
		 {
			 window.alert('An Intervention Code must be selected before saving.');
			 $('#_interventionCode').focus();
			 return false;
		 }
		 
		 if ($.trim($('#_comment').val()) == '')
		 {
			 window.alert('A comment must be entered before saving.');
			 $('#_comment').focus();
			 return false;
		 }
		 
		 if ($('#_status').val() == '-1')
		 {
			 window.alert('A Status code must be selected before saving.');
			 $('#_status').focus();
			 return false;
		 }
		 
		 if ($('#_physician').val() == '-1')
		 {
			 window.alert('A Physcian must be selected before saving.');
			 $('#_physician').focus();
			 return false;
		 }
		 
		 if ($('#_unitPatientLocationId').val() == '-1')
		 {
			 window.alert('The Unit/Patient Location must be selected before saving.');
			 $('#_unitPatientLocationId').focus();
			 return false;
		 }
		 
		 if ($('#_pharmacist').val() == '-1')
		 {
			 window.alert('A Pharmacist must be selected before saving.');
			 $('#_pharmacist').focus();
			 return false;
		 }
		 
		 if ($('input[name=ordered_drug_id]').val() == '')
		 {
			 window.alert('Ordered drug is required.');
			 $('#_orderedDrugText').focus();
			 return false;
		 }

		 return true;
	}
	
	
	function checkAdvancedFields()
	{
		
		if ($.trim($('#_orderedUnitCost').val()) == '')
		{
			window.alert('Ordered Unit Cost is required.');
			$('#_orderedUnitCost').focus();
			return false;
		}
				
		if ($.trim($('#_orderedDosesPerDay').val()) == '')
		{
			window.alert('Ordered Doses Per Day is required.');
			$('#_orderedDosesPerDay').focus();
			return false;
		}
		 
		var riskMitigation = $('#_interventionCode :selected').text().indexOf('(r)') > 0;
		if (riskMitigation)
			return true;
		
		if ($('input[name=recommended_drug_id]').val() == '')
		{
			window.alert('Recommended drug is required.');
			$('#_recommendedDrugText').focus();
			return false;
		}
		
		if ($('#_recommendedDrugFrequencyId').val() == '-1')
		{
			window.alert('Recommened Drug Frequency is required.');
			$('#_recommendedDrugFrequencyId').focus();
			return false;
		}
		
		if ($.trim($('#_recommendedUnitCost').val()) == '')
		{
			window.alert('Recommended Unit Cost is required.');
			$('#_recommendedUnitCost').focus();
			return false;
		}
		
		if ($.trim($('#_recommendedDosesPerDay').val()) == '')
		{
			window.alert('Recommended Doses Per Day is required.');
			$('#_recommendedDosesPerDay').focus();
			return false;
		}
		
		if ($.trim($('#_daysOfTx').val()) == '')
		{
			window.alert('Days Of Tx is required.');
			$('#_daysOfTx').focus();
			return false;
		}
		
		if ($.trim($('#_currentTxDay').val()) == '')
		{
			window.alert('Current Tx Day is required.');
			$('#_currentTxDay').focus();
			return false;
		}
		
		 return true;
	}

